package com.example.jcpmpose

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Spa
import androidx.compose.material3.Card
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jcpmpose.ui.theme.JcpmposeTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


@Preview
@Composable
fun SearchBar(modifier: Modifier = Modifier) {

    TextField(
        value = "",
        onValueChange = {},
        modifier = modifier
            .heightIn(min = 56.dp)
            .fillMaxWidth(),
        placeholder = {
            Text("Search")
        },
        leadingIcon = {
            Icon(
                imageVector = Icons.Default.Search,
                contentDescription = null
            )
        },
        colors = TextFieldDefaults.colors(
            unfocusedContainerColor = MaterialTheme.colorScheme.surface,
            focusedContainerColor = MaterialTheme.colorScheme.surface,
        )
    )
}


@Preview(showBackground = true)
@Composable
fun AlignYourBodyElement(modifier: Modifier = Modifier) {

    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            painter = painterResource(R.drawable.ic_launcher_background),
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(88.dp)
                .clip(CircleShape)
        )
        Text(
            text = "Text",
            modifier = Modifier.paddingFromBaseline(24.dp, bottom = 8.dp),
            style = MaterialTheme.typography.bodyMedium
        )
    }
}

@Preview(showBackground = true)
@Composable
fun FavoriteCollectionCard(modifier: Modifier = Modifier) {

    Surface(
        shape = MaterialTheme.shapes.medium,
        modifier = modifier.width(255.dp),
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(R.drawable.ic_launcher_background),
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier.size(80.dp)
            )
            Text(
                "Self-message",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(horizontal = 16.dp)
            )
        }

    }
}

@Preview(showBackground = true)
@Composable
fun AlignHYourBodyRow(modifier: Modifier = Modifier) {

    LazyRow(
        modifier = modifier,
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        contentPadding = PaddingValues(start = 16.dp, end = 16.dp)
    ) {
        items(10) {
            AlignYourBodyElement()
        }
    }
}

@Composable
@Preview(showBackground = true)
fun FavoriteCollectionsGrid(
    modifier: Modifier = Modifier
) {
    LazyHorizontalGrid(
        rows = GridCells.Fixed(2),
        modifier = modifier.height(168.dp),
        contentPadding = PaddingValues(horizontal = 16.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(10) {
            FavoriteCollectionCard()
        }
    }
}

@Composable
fun HomeSection(title: String, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    Column(
        modifier = modifier
    ) {
        Text(
            text = title,
            modifier = Modifier
                .paddingFromBaseline(top = 40.dp, bottom = 16.dp)
                .padding(horizontal = 16.dp),
            style = MaterialTheme.typography.titleMedium
        )
        content()
    }
}

@Composable
fun SoothBottomNavigation(modifier: Modifier = Modifier,
                          onNavChange: (Int) -> Unit = {}
) {
    NavigationBar(
        modifier = modifier,
        containerColor = MaterialTheme.colorScheme.surfaceVariant
    ) {
        NavigationBarItem(
            icon = {
                Icon(
                    imageVector = Icons.Default.Spa,
                    contentDescription = null
                )
            },
            label = {
                Text("Home")
            },
            selected = true,
            onClick = { onNavChange(0) }
        )
        NavigationBarItem(
            icon = {
                Icon(
                    imageVector = Icons.Default.AccountCircle,
                    contentDescription = null
                )
            },
            label = {
                Text("Profile")
            },
            selected = true,
            onClick = { onNavChange(1) }
        )
    }
}

@Composable
@Preview
fun Tasks(modifier: Modifier = Modifier) {
    Card(
        modifier = modifier.padding(5.dp)
    ) {
        LazyColumn(
            modifier = modifier
                .background(MaterialTheme.colorScheme.background)
                .height(256.dp)
                .shadow(1.dp)
        ) {
            items(10) {
                Task(task = "Task for list At $it")
            }
        }
    }

}

@Composable
fun Task(modifier: Modifier = Modifier, task: String) {
    var expanded by rememberSaveable { mutableStateOf(false) }
    Row(
        modifier = modifier
            .fillMaxWidth()
            .heightIn(min = 64.dp)
            .padding(start = 16.dp)
            .clickable(onClick = { expanded = !expanded }),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(
            imageVector = Icons.Filled.Check,
            contentDescription = null,
            modifier = Modifier.size(24.dp)
        )
        Column(
            modifier = Modifier.animateContentSize()
                .padding(16.dp)
        ) {
            val fontBold = MaterialTheme.typography.bodyMedium
                .copy(fontWeight = FontWeight.Bold)
            Text(
                text = task,
                style = if (expanded) fontBold else fontBold.copy(fontWeight = FontWeight.Normal),
            )
            if (expanded) {
                Text(
                    text = """
                    This is a long description of what needs to be done                        
                    """.trimIndent(),
                )
            }
        }


    }
}

@Composable
@Preview(showBackground = true)
@Preview(showBackground = true, heightDp = 180)
fun HomeScreen(modifier: Modifier = Modifier) {

    val scrollState = rememberScrollState()
    val expand = scrollState.isScrollingUp()

    var showEditMessage by remember { mutableStateOf(false) }
    val coroutineScope = rememberCoroutineScope()
    suspend fun shownEditMessage() {
        if (!showEditMessage) {
            showEditMessage = true
            delay(3000)
            showEditMessage = false
        }
    }

    Column(
        modifier = modifier.fillMaxSize()
    ) {
        SearchBar(modifier = Modifier.padding(16.dp))
        Box {

            Column(
                modifier = Modifier.verticalScroll(scrollState)
            ) {
                HomeSection(title = "Align your body") {
                    AlignHYourBodyRow()
                }
                HomeSection(title = "Favorite collections") {
                    FavoriteCollectionsGrid()
                }
                HomeSection(title = "Align your mind") {
                    Tasks()
                }
            }
            ExpandableButton(expand) {
                coroutineScope.launch {
                    shownEditMessage()
                }
            }
            EditMessage(showEditMessage) {
                showEditMessage = false
            }

        }

    }
}

@Composable
fun EditMessage(shown: Boolean, onDismiss: () -> Unit = {}) {
    AnimatedVisibility(shown) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp),
            color = MaterialTheme.colorScheme.secondary,
            shape = RectangleShape,
            shadowElevation = 10.dp
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 16.dp, end = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    "Edit message",
                    modifier = Modifier.weight(1.0f)
                )

                TextButton(onClick = onDismiss) {
                    Text(
                        "Dismiss",
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }
        }
    }
}

@Composable
private fun BoxScope.ExpandableButton(expand: Boolean, onClick: () -> Unit = {}) {
    FloatingActionButton(
        onClick = onClick,
        modifier = Modifier
            .heightIn(max = 64.dp)
            .align(Alignment.BottomEnd)
            .padding(end = 16.dp, bottom = 16.dp),
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.padding(start = 10.dp, end = 10.dp)
        ) {
            Icon(
                imageVector = Icons.Filled.Edit,
                contentDescription = null
            )
            AnimatedVisibility(
                visible = expand
            ) {
                Text(
                    text = "Edit",
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(8.dp)
                )
            }
        }
    }
}

@Composable
private fun ScrollState.isScrollingUp(): Boolean {
    var previousValue by remember(this) { mutableIntStateOf(value) }

    return remember(this) {
        derivedStateOf {
            if (previousValue != value) {
                previousValue > value
            } else {
                false
            }.also {
                previousValue = value
            }
        }
    }.value
}

@Composable
@Preview(showBackground = true)
fun SoothApp() {
    JcpmposeTheme {
        var tabPage by remember { mutableIntStateOf(0) }
        val backgroundColor by animateColorAsState(
            targetValue = if (tabPage == 0) MaterialTheme.colorScheme.background else MaterialTheme.colorScheme.tertiaryContainer,
            label = "background color"
        )
        Scaffold(
            bottomBar = {
                SoothBottomNavigation(
                    onNavChange = {
                        tabPage = it
                    },
                    modifier = Modifier.background(MaterialTheme.colorScheme.surface)
                )
            },
            containerColor = backgroundColor
        ) { paddingValues ->
            HomeScreen(
                Modifier
                    .padding(paddingValues = paddingValues)
                    .background(backgroundColor)
            )
        }
    }

}

